package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户认证接口")
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173", allowedHeaders = {"Authorization", "Content-Type"}, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
@Slf4j
public class AuthController {
    private final UserService userService;
    
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody LoginRequest request) {
        log.info("收到登录请求: username={}, password长度={}", request.getUsername(), request.getPassword().length());
        Map<String, Object> response = new HashMap<>();
        try {
            String token = userService.login(request.getUsername(), request.getPassword());
            Map<String, String> data = new HashMap<>();
            data.put("token", token);
            
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", data);
            log.info("登录成功: username={}, token={}", request.getUsername(), token);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("登录失败: username={}, error={}", request.getUsername(), e.getMessage(), e);
            response.put("code", 400);
            response.put("message", "登录失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(400).body(response);
        }
    }
    
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody RegisterRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            userService.register(request.getUsername(), request.getPassword());
            response.put("code", 200);
            response.put("message", "注册成功");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(400).body(response);
        }
    }
}

@Data
class RegisterRequest {
    private String username;
    private String password;
}

@Data
class LoginRequest {
    private String username;
    private String password;
} 